package com.aacar.service.impl;

import com.aacar.dao.SeqDao;
import com.aacar.entity.SeqNo;
import com.aacar.service.SeqService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

@Repository("seqService")
public class SeqServiceImpl implements SeqService {
	
	
	static final SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
	
	private String serviceDate = df.format(new Date());
	
	private ConcurrentHashMap<String,Integer> nextNoMap = new ConcurrentHashMap<>();
	
	private int remainNum = 0;
	
	private int perNum = 200;
	
	
	@PostConstruct
    public void init() {
		nextNoMap.put("0", 1);
    }
	
    @Autowired
    private SeqDao seqDao;
    
    
    
	@Override
	public synchronized String getSeqNoFromMem(String seq_class, int num) {
		
		String curDat = df.format(new Date());
		
		int nextNo = this.nextNoMap.get(seq_class);

	    if ((!StringUtils.equals(this.serviceDate, curDat)) || 
	      (nextNo % this.perNum == 0)) {
		      int seqno = this.getLogNoFromDB(seq_class, this.perNum + num);
		      nextNo = seqno;
		      this.remainNum = (this.perNum + num);
		      this.serviceDate = curDat;
	    }
	    nextNo += num;
	    this.nextNoMap.put(seq_class, nextNo);
	    this.remainNum -= num;
	    
	    System.out.println("当前线程为：" + Thread.currentThread().getName() + 
	    		"获取seqNo为:" + nextNo);
	    return curDat + StringUtils.leftPad(String.valueOf(nextNo), 6, '0');
	}



	@Override
	public int getLogNoFromDB(String seq_class, int num) {
		String logNo = seqDao.getSeqNo(seq_class);

		System.out.println("当前库表seqNo是:" + logNo);

		int iLogNo = NumberUtils.toInt(logNo);

		logNo = StringUtils.leftPad(String.valueOf(iLogNo+num), 6, '0');

		// add by mc 超过6位自动回执0
		if(Integer.parseInt(logNo) > 999799){
			logNo = "000000";
		}

		SeqNo seqModel = new SeqNo();
		seqModel.setSeqClass(seq_class);
		seqModel.setSeqNo(logNo);


		seqDao.update(seqModel);

		return NumberUtils.toInt(logNo);
	}

}
